package com.njit.WeStudy.control;

import com.njit.WeStudy.dao.UserMapper;
import com.njit.WeStudy.dataobject.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

/**
 * @author yuruiqiao
 * @date 2020/1/26
 * @description 用于更改用户昵称,用户头像等
 */
@RestController
public class UserUpdateController {

    @Resource
    private UserMapper userMapper;

    @RequestMapping(path = "/updateUsername")
    public String updateUsername(@RequestParam String username, HttpSession session){
        int userId = ((User)session.getAttribute("user")).getUserId();
        try{
            userMapper.updateOneById("user_name",username,userId);
            //更新session
            session.setAttribute("user",userMapper.selectByPrimaryKey(userId));
            return "修改成功";
        }catch (Exception e){
            e.printStackTrace();
        }
        return "修改失败";
    }

    @RequestMapping(path = "/uploadHeadImage")
    public String uploadHeadImage(HttpServletRequest request, @RequestParam("file") MultipartFile file, HttpSession session) {

        int userId = ((User)session.getAttribute("user")).getUserId();
        //文件的文件名加扩展名
        String originalFilename = file.getOriginalFilename();
        //获取文件名的后缀
        String fileType = Objects.requireNonNull(originalFilename).substring(originalFilename.lastIndexOf(".")).substring(1);
        //上传的真实路径
        String filePath =request.getServletContext().getRealPath("upload/"+userId+"/"+fileType);
        // 获取上传文件名,并生成新的,唯一的文件名
        String filename = UUID.randomUUID()+"."+fileType;
        // 新建文件
        File filepath = new File(filePath, filename);
        // 判断路径是否存在，如果不存在就创建一个
        if (!filepath.getParentFile().exists()) {
            boolean isSuccess = filepath.getParentFile().mkdirs();
            if (!isSuccess) {
                System.out.println("mkdirs-error");
            }
        }
        try {

            file.transferTo(new File(filePath + File.separator + filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String finalPath = "/upload/"+userId+"/"+fileType+"/" +filename;
        try{
            userMapper.updateOneById("head_image",finalPath,userId);
            //更新session
            session.setAttribute("user",userMapper.selectByPrimaryKey(userId));
        }catch (Exception e){
            e.printStackTrace();
        }
        return finalPath;
    }
}
